package com.server.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.server.date.DateType;
import com.server.date.DateUtil;
import com.server.service.ICaseService;
import com.server.service.ICommonDataService;
import com.server.service.IUserAssignmentService;

@Service("CaseService")
public class CaseService implements ICaseService {
	
	private String tableName = "education.case_warehouse";
	
	@Autowired
	private IUserAssignmentService userAssignmentService;

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ICommonDataService commonDataService;
	
	 /**
	 * 提交评估
	 * @param ids
	 * @param operator
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月15日
	 */
	@Override
	public Integer toEstimate(String ids,String operator){
		StringBuffer idsBuffer = new StringBuffer();
		String[] split = ids.split(",");
		for(String id : split){
			Boolean estimateAssi = userAssignmentService.estimateAssi(Integer.parseInt(id), 3, 1);
			if (estimateAssi) {
				if (idsBuffer.length() > 0) {
					idsBuffer.append(",");
				}
				idsBuffer.append(id);
			}
		}
		if (idsBuffer.length() <= 0) {
			return 0;
		}
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		String sql = "update %s set state=1,mender='%s',updateTime='%s' where id in('%s')";
		return jdbcTemplate.update(String.format(sql, tableName,operator,dateStr,idsBuffer.toString().replaceAll(",", "','")));
	}
	@Override
	public Integer delete(String ids,String operator){
		String sql = "delete from %s where id in('%s')";
		return jdbcTemplate.update(String.format(sql, tableName, ids.replaceAll(",", "','")));
	}
	@Override
	public Integer getId(Object uuid){
		String sql = "select id from %s where uuid='%s'";
		Integer id = jdbcTemplate.queryForObject(String.format(sql, tableName,uuid.toString()), Integer.class);
		return id;
	}
	
	@Override
	public boolean updateState(String id, int state, String operator, Boolean isAudit) {
		boolean isSuccess = true;
		String sql = null;
		if (isAudit) {
			sql = "update %s set state=%s,auditor='%s',auditTime='%s' where id=%s";
		}else {
			sql = "update %s set state=%s,evaluator='%s',evalueTime='%s' where id=%s";
		}
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		try {
			int update = jdbcTemplate.update(String.format(sql, tableName,state,operator,dateStr,id));
			if(update <= 0){
				isSuccess = false;
			}
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
}
